package com.kantboot.business.shop.service.impl;

import com.kantboot.business.shop.domain.entity.BusShopAddressInUserAccount;
import com.kantboot.business.shop.repository.BusShopAddressInUserAccountRepository;
import com.kantboot.business.shop.service.IBusShopAddressInUserAccountService;
import com.kantboot.user.account.service.IUserAccountService;
import com.kantboot.util.common.exception.BaseException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BusShopAddressInUserAccountServiceImpl implements IBusShopAddressInUserAccountService {

    @Resource
    private IUserAccountService userAccountService;

    @Resource
    private BusShopAddressInUserAccountRepository repository;

    @Override
    public void saveSelf(BusShopAddressInUserAccount address) {
        // 查询这个商品是不是自己的
        BusShopAddressInUserAccount busShopAddressInUserAccount = repository.findBy(address.getId());
        if(address.getId()!=null&&busShopAddressInUserAccount==null){
            // 非法请求
            throw BaseException.of("illegalRequest", "非法请求");
        }
        if(address.getId()!=null&&!busShopAddressInUserAccount.getUserAccountId().equals(userAccountService.getSelf().getId())){
            // 非法请求
            throw BaseException.of("illegalRequest", "非法请求");
        }

        address.setUserAccountId(userAccountService.getSelf().getId());
        if(address.getIsDefault()!=null&&address.getIsDefault()){
            // 如果设置为默认地址，先将原来的默认地址设置为非默认
            repository.updateIsDefaultByUserAccountId(false, address.getUserAccountId());
        }
        repository.save(address);
    }

    @Override
    public List<BusShopAddressInUserAccount> getSelf() {
        return repository.getByUserAccountId(userAccountService.getSelf().getId());
    }

    @Override
    public void deleteSelf(Long id) {
        // 查询这个商品是不是自己的
        BusShopAddressInUserAccount busShopAddressInUserAccount = repository.findBy(id);
        if(busShopAddressInUserAccount==null){
            // 非法请求
            throw BaseException.of("illegalRequest", "非法请求");
        }
        if(!busShopAddressInUserAccount.getUserAccountId().equals(userAccountService.getSelfId())){
            // 非法请求
            throw BaseException.of("illegalRequest", "非法请求");
        }

        repository.delete(busShopAddressInUserAccount);
    }
}
